$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/tenant/list',
        datatype: "json",
        colModel: [			
			{ label: '租户ID', name: 'tenantId', index: "tenant_id", width: 45, key: true },
			{ label: '邮箱', name: 'tenantEmail', width: 75 },
			{ label: '名称', name: 'tenantName', width: 75 },
			{ label: '地址', name: 'tenantAddress', width: 90 },
			{ label: '电话', name: 'tenantTel', width: 100 },
			{ label: '最后修改时间', name: 'lastUptime', width: 100 },
			{ label: '状态', name: 'activeState', width: 80, formatter: function(value, options, row){
				return value ==1 ?
					'<span class="label label-danger">正常</span>' :
					'<span class="label label-success">禁用</span>';
			}},
			{ label: '创建时间', name: 'createTime', index: "create_time", width: 80}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var vm = new Vue({
    el:'#rrapp',
    data:{
        q:{
            tenantName: null
        },
        showList: true,
        title:null,
		tenant:{}
    },
    methods: {
        query: function () {
            vm.reload();
        },
        add: function(){
            vm.showList = false;
            vm.title = "新增";
			vm.tenant={
                tenantId:null,
                tenantNo:null,
                tenantEmail:null,
                tenantName:"",
                tenantAddress:"",
                tenantTel:"",
                createTime:null,
                lastUptime:null,
                activeState:2,
                activedTime:"",
                abateTime:""
			}
        },
        update: function () {
            var tenantId = getSelectedRow();
            if(tenantId == null){
                return ;
            }
            //平台租户不可修改
            if(tenantId==1){
                alert("平台管理员租户不可修改！");
                return;
            }
            vm.showList = false;
            vm.title = "修改";

            vm.getTenant(tenantId);
        },
        del: function () {
            var tenantIds = getSelectedRows();
            if(tenantIds == null){
                return ;
            }
            if(tenantIds.indexOf("1")>-1){
                alert("平台管理员租户不可删除！");
                return;
            }
            confirm('确定要删除选中的记录？', function(){
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/tenant/delete",
                    contentType: "application/json",
                    data: JSON.stringify(tenantIds),
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        linkshare:function () {
            var tenantId = getSelectedRow();
            if(tenantId == null){
                return ;
            }
            vm.getTenant(tenantId,function (_tenant) {
                var linkurl=_tenant.tenantId+"###"+_tenant.tenantEmail+"###"+_tenant.tenantName;
                linkurl=base64encode(linkurl);
                linkurl="http://"+this.location.host+"/?tenant="+linkurl;
                showDialog(linkurl,function () {
                })
            });
        },//租户系统链接分享
        saveOrUpdate: function () {
            if(vm.validator()){
                return ;
            }
            var url = vm.tenant.tenantId == null ? "sys/tenant/save" : "sys/tenant/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.tenant),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(){
                            vm.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        getTenant: function(tenantId,_callfun){
            $.get(baseURL + "sys/tenant/info/"+tenantId, function(r){
                vm.tenant = r.tenant;
                if(_callfun!=null){
                    _callfun(vm.tenant);
                }
            });
        },//获取租户信息
        reload: function () {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'tenantName': vm.q.tenantName},
                page:page
            }).trigger("reloadGrid");
        },//重新加载租户列表
        validator: function () {
            if(isBlank(vm.tenant.tenantEmail)){
                alert("邮箱不能为空");
                return true;
            }
            if(!validator.isEmail(vm.tenant.tenantEmail)){
                alert("邮箱格式不正确");
                return true;
            }

            if(isBlank(vm.tenant.tenantName)){
                alert("租户名不能为空");
                return true;
            }

            if(isBlank(vm.tenant.tenantAddress)){
                alert("租户地址不能为空");
                return true;
            }

            if(isBlank(vm.tenant.tenantTel)){
                alert("租户电话不能为空");
                return true;
            }
            //产生新的租户编号
            if(vm.tenant.tenantId!=null && vm.tenant.tenantId!=""){}else{
            	vm.tenant.tenantNo=new GUID().newGUID();
			}
			//初始化创建时间和最后修改时间
			if(vm.tenant.createTime!=null && vm.tenant.createTime!=""){
                vm.tenant.lastUptime=formatDate("yyyy-MM-dd HH:mm:ss");
			}else{
                vm.tenant.createTime=formatDate("yyyy-MM-dd HH:mm:ss");
                vm.tenant.lastUptime=vm.tenant.createTime
			}

        }
    }
});

/**
 * GUID 产生对象
 * @constructor
 */
function GUID() {
    this.date = new Date();   /* 判断是否初始化过，如果初始化过以下代码，则以下代码将不再执行，实际中只执行一次 */
    if (typeof this.newGUID != 'function') {   /* 生成GUID码 */
        GUID.prototype.newGUID = function () {
            this.date = new Date(); var guidStr = '';
            for (var i = 0; i < 9; i++) {
                guidStr += Math.floor(Math.random() * 16).toString(16);
            }
            guidStr=formatDate("yyyyMMddHHmmss")+guidStr;
            return guidStr;
        }
    }
}

function formatDate(format) {
    var date=new Date();
    if (!date) return;
    if (!format) format = "yyyy-MM-dd";
    switch(typeof date) {
        case "string":
            date = new Date(date.replace(/-/, "/"));
            break;
        case "number":
            date = new Date(date);
            break;
    }
    if (!date instanceof Date) return;
    var dict = {
        "yyyy": date.getFullYear(),
        "M": date.getMonth() + 1,
        "d": date.getDate(),
        "H": date.getHours(),
        "m": date.getMinutes(),
        "s": date.getSeconds(),
        "f": date.getMilliseconds(),
        "MM": ("" + (date.getMonth() + 101)).substr(1),
        "dd": ("" + (date.getDate() + 100)).substr(1),
        "HH": ("" + (date.getHours() + 100)).substr(1),
        "mm": ("" + (date.getMinutes() + 100)).substr(1),
        "ss": ("" + (date.getSeconds() + 100)).substr(1),
        "fff":("" + (date.getMilliseconds() + 1000)).substr(1)
    };
    return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?|fff?)/g, function() {
        return dict[arguments[0]];
    });
}